package com.gjy.nwpufindseats;

import java.util.ArrayList;

import com.gjy.nwpufindseats.util.JwNetSpider;
import com.gjy.nwpufindseats.Fragment.Fragment_grade;
import com.gjy.nwpufindseats.Fragment.Fragment_grade_info;
import com.gjy.nwpufindseats.Fragment.Fragment_palsy;
import com.gjy.nwpufindseats.baseData.AllGrade;
import com.gjy.nwpufindseats.baseData.Session;
import com.gjy.nwpufindseats.util.NetInfo;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class Activity_grade extends SlidingFragmentActivity implements OnClickListener

{
	protected SlidingMenu mSlidingMenu;
	private ImageButton ivTitleBtnLeft;
	private TextView commonTitle;
	private TableLayout gradeTableLayout;
	public static NetInfo netInfo = new NetInfo();
	public static ArrayList<String> gradeArrayList=new ArrayList<String>();
	public static ArrayList<AllGrade> allGrades=new ArrayList<AllGrade>();
	Boolean end=false;//是否获得正确数据，true为正确数据。
	Handler handler = new Handler();
	ProgressBar progressBar;
	public static SharedPreferences preferences;
	public String xhString;
	public String passwordString;
	public static int loginInfo;
	public static Context mainContext;
	private Handler handlerMsg;
	private Intent intent;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_grade);
		setBehindContentView(R.layout.main_left_layout);	//由于是对SlidingFragmentActivity的继承，必须由此代码		
		getSlidingMenu().setBehindWidth(0);//滑动为0，即禁止左滑
		
		
		mainContext = this;
		commonTitle = (TextView) findViewById(R.id.ivTitleName);
		commonTitle.setText("成绩查询");
		ivTitleBtnLeft = (ImageButton)this.findViewById(R.id.ivTitleBtnLeft);
		ivTitleBtnLeft.setOnClickListener(this);
		    	Fragment newContentFragment = new Fragment_grade();
				switchFragment(newContentFragment);
		    	setGradeTableLayout((TableLayout) findViewById(R.id.gradesTable));
		    	progressBar = (ProgressBar)findViewById(R.id.progressBar);
		    	preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
		    	xhString = preferences.getString("xh", "0");//未登录，则返回0，登录返回学号
		    	passwordString = preferences.getString("password", "0");
		    	
		    	handlerMsg=new Handler(){
		    		@SuppressWarnings("unused")
					private int message;
		
					public void handleMessage(Message msg){
		    		     
					message = (Integer)msg.obj;
			    		if(loginInfo==0)
						{
			    			onBackPressed();
							Toast.makeText(mainContext, "已保存账户密码错误，请修改", Toast.LENGTH_LONG).show();
						}
						else if(loginInfo==1){
							
							Toast.makeText(mainContext, "教务网瘫痪了。。。", Toast.LENGTH_SHORT).show();

						}
						else{
							
						}
		    		}
		    		 };
		    	Thread tProgress = new Thread()
		    	{
		    		public void run()
		    		{
		    			
		    			while (!end) 
		                {
		                }
								handler.post(new Runnable()
				                {
				                     public void run()
				                     {
				                    	 intent = getIntent(); 
				                          if(end){//获得正确数据，并且跳转至数据显示页面
				              				Bundle bundlef = new Bundle();
				              				if(3==intent.getIntExtra("gradeType", 0))
				              				{
				              					Session session = Session.getSession();
				              			        session.put("allGrades", allGrades);
				              				}
				              				else {
				              					bundlef.putStringArrayList("grade_info", gradeArrayList); 
											}
				              				bundlef.putStringArrayList("grade_info", gradeArrayList); 
				              				bundlef.putInt("gradeType",intent.getIntExtra("gradeType", 0));
				              		    	Fragment newContent= new Fragment_grade_info();
				              		    	newContent.setArguments(bundlef);
				              		    	switchFragment(newContent);
				                          }
				                     }
				                });  
							} 		
		    	};
		    	tProgress.start();
		    	Thread tGet =new Thread()
				{
		    		JwNetSpider jwNetSpider=new JwNetSpider();
		    		@SuppressWarnings("static-access")
					public void run()
					{
						 intent = getIntent(); 
						try 
						{
							if(0==intent.getIntExtra("gradeType", 0))
							{
								allGrades.add(new AllGrade("0", null));
								gradeArrayList = jwNetSpider.getGrade(mainContext,xhString,passwordString);
							}							
							else if(1==intent.getIntExtra("gradeType", 0)) {
								allGrades.add(new AllGrade("0", null));
								gradeArrayList = jwNetSpider.getAllGrade(mainContext,xhString,passwordString);
							}
							else if(2==intent.getIntExtra("gradeType", 0))
							{
								allGrades.add(new AllGrade("0", null));
								gradeArrayList = jwNetSpider.getbjgGrade(mainContext,xhString,passwordString);
							}
							else {
								gradeArrayList.add("2");//防止后面程序因为gradeArrayList为空而崩溃
								allGrades = jwNetSpider.getAllJgGrade(mainContext,xhString,passwordString);
								if(allGrades.isEmpty())//值为空，传值
								{
									loginInfo = 1;//网站数据错误，跳转至"瘫痪"页面
									Message message = Message.obtain();
									message.obj=loginInfo;
									handlerMsg.sendMessage(message);
								}
							}
							
							if("0".equals(gradeArrayList.get(0)) )//保存的密码有误
							{
								loginInfo = 0;//跳转至登录信息页面，以修改数据
								Message message = Message.obtain();
								message.obj=loginInfo;
								//通过Handler发布传送消息，handler
								handlerMsg.sendMessage(message);
							}
							else if("1".equals(gradeArrayList.get(0))){//网页信息有误
								loginInfo = 1;//网站数据错误，跳转至"瘫痪"页面
								Message message = Message.obtain();
								message.obj=loginInfo;
								handlerMsg.sendMessage(message);
								Fragment newContentFragment = new Fragment_palsy();
								switchFragment(newContentFragment);
							}							
							else{
								loginInfo = 2;	
								end=true;
							}
							
						}
						catch ( Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
				};
		
					tGet.start();	
    	}
     
     
     public void switchFragment(Fragment fragment) {
         getSupportFragmentManager()
         .beginTransaction()
         .replace(R.id.content_frame, fragment)
         .commit();
	 }
     
     public Handler getHandler(){
    	 return this.handler;
    	 }


	public TableLayout getGradeTableLayout() {
		return gradeTableLayout;
	}


	public void setGradeTableLayout(TableLayout gradeTableLayout) {
		this.gradeTableLayout = gradeTableLayout;
	}	

	public void onClick(View v) {
		Fragment newContent = new Fragment_grade();;
		Bundle bundle = new Bundle();	
		switch (v.getId()) {
			case R.id.ivTitleBtnLeft:
				onBackPressed();
				break;
			case R.id.thisTerm:
				bundle.putInt("gradeType",  0);//0代表本学期成绩
				newContent.setArguments(bundle);
				switchFragment(newContent);
				break;
			case R.id.properties:
				bundle.putInt("gradeType",  1);//1代表属性成绩
				newContent.setArguments(bundle);
				switchFragment(newContent);
				break;
			case R.id.notPass:
				bundle.putInt("gradeType",  2);//2代表不及格
				newContent.setArguments(bundle);
				switchFragment(newContent);
			break;
			case R.id.pass:
				bundle.putInt("gradeType",  3);//3代表所有及格成绩
				newContent.setArguments(bundle);
				switchFragment(newContent);
				break;	
			default:
			break;
		}		
	}


}
